from flask import request, jsonify
from flask import request, jsonify, current_app
from . import api_bp

# 从current_app获取db和模型引用
def get_db_and_models():
    db = current_app.db
    User = current_app.User
    return db, User

# 用户登录API
@api_bp.route('/user/login', methods=['POST'])
def user_login():
    # 获取db和模型引用
    db, User = get_db_and_models()
    
    data = request.json
    
    if not data or 'phone' not in data:
        return jsonify({'success': False, 'message': '缺少手机号'}), 400
    
    phone = data['phone']
    
    # 检查用户是否存在
    user = User.query.filter_by(phone=phone).first()
    
    if not user:
        # 如果用户不存在，则创建新用户
        user = User(phone=phone)
        db.session.add(user)
        db.session.commit()
        
    # 返回用户信息
    return jsonify({
        'success': True,
        'data': {
            'id': user.id,
            'phone': user.phone,
            'nickname': user.nickname,
            'avatar': user.avatar
        }
    })

# 获取用户信息API
@api_bp.route('/user/info', methods=['GET'])
def get_user_info():
    # 获取db和模型引用
    db, User = get_db_and_models()
    
    user_id = request.args.get('user_id')
    
    if not user_id:
        return jsonify({'success': False, 'message': '缺少用户ID'}), 400
    
    # 查询用户信息
    user = User.query.get(user_id)
    
    if not user:
        return jsonify({'success': False, 'message': '用户不存在'}), 404
    
    # 返回用户信息
    return jsonify({
        'success': True,
        'data': {
            'id': user.id,
            'phone': user.phone,
            'nickname': user.nickname,
            'avatar': user.avatar
        }
    })

# 更新用户信息API
@api_bp.route('/user/update', methods=['POST'])
def update_user_info():
    # 获取db和模型引用
    db, User = get_db_and_models()
    
    data = request.json
    
    if not data or 'user_id' not in data:
        return jsonify({'success': False, 'message': '缺少用户ID'}), 400
    
    user_id = data['user_id']
    
    # 查询用户
    user = User.query.get(user_id)
    
    if not user:
        return jsonify({'success': False, 'message': '用户不存在'}), 404
    
    # 更新用户信息
    if 'nickname' in data:
        user.nickname = data['nickname']
    if 'avatar' in data:
        user.avatar = data['avatar']
    if 'openid' in data:
        user.openid = data['openid']
    
    db.session.commit()
    
    return jsonify({'success': True, 'message': '用户信息更新成功'})